package com.yijiaw.service;

import com.yijiaw.dao.AdminDAO;

import com.yijiaw.domain.Admin;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

/**
 * Spring service that handles CRUD requests for Admin entities
 * 
 */

@Service("AdminService")
@Transactional
public class AdminServiceImpl implements AdminService {

	/**
	 * DAO injected by Spring that manages Admin entities
	 * 
	 */
	@Autowired
	private AdminDAO adminDAO;

	/**
	 * Instantiates a new AdminServiceImpl.
	 *
	 */
	public AdminServiceImpl() {
	}

	/**
	 * Delete an existing Admin entity
	 * 
	 */
	@Transactional
	public void deleteAdmin(Admin admin) {
		adminDAO.remove(admin);
		adminDAO.flush();
	}

	/**
	 * Return all Admin entity
	 * 
	 */
	@Transactional
	public List<Admin> findAllAdmins(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Admin>(adminDAO.findAllAdmins(startResult, maxRows));
	}

	/**
	 * Return a count of all Admin entity
	 * 
	 */
	@Transactional
	public Integer countAdmins() {
		return ((Long) adminDAO.createQuerySingleResult("select count(o) from Admin o").getSingleResult()).intValue();
	}

	/**
	 */
	@Transactional
	public Admin findAdminByPrimaryKey(Integer id) {
		return adminDAO.findAdminByPrimaryKey(id);
	}

	/**
	 * Save an existing Admin entity
	 * 
	 */
	@Transactional
	public void saveAdmin(Admin admin) {
		Admin existingAdmin = adminDAO.findAdminByPrimaryKey(admin.getId());

		if (existingAdmin != null) {
			if (existingAdmin != admin) {
				existingAdmin.setId(admin.getId());
				existingAdmin.setUsername(admin.getUsername());
				existingAdmin.setPassword(admin.getPassword());
			}
			admin = adminDAO.store(existingAdmin);
		} else {
			admin = adminDAO.store(admin);
		}
		adminDAO.flush();
	}

	/**
	 * Load an existing Admin entity
	 * 
	 */
	@Transactional
	public Set<Admin> loadAdmins() {
		return adminDAO.findAllAdmins();
	}
	
	@Transactional
	public Admin findAdmin(String username, String password) {
		List<Admin> list = adminDAO.executeQuery("from Admin where username = ? and password = ?", username, password);
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}
}
